// 您提供了与基于主色生成和应用新样式、从 element-plus 获取原始样式以及更新 CSS 中颜色相关的代码。以下是您的代码的优化版本：

import color from 'css-color-function'
import rgbHex from 'rgb-hex'
import axios from 'axios'

const objJson = {
    "shade-1": "color(primary shade(10%))",
    "light-1": "color(primary tint(10%))",
    "light-2": "color(primary tint(20%))",
    "light-3": "color(primary tint(30%))",
    "light-4": "color(primary tint(40%))",
    "light-5": "color(primary tint(50%))",
    "light-6": "color(primary tint(60%))",
    "light-7": "color(primary tint(70%))",
    "light-8": "color(primary tint(80%))",
    "light-9": "color(primary tint(90%))",
    "subMenuHover": "color(primary tint(70%))",
    "subMenuBg": "color(primary tint(80%))",
    "menuHover": "color(primary tint(90%))",
    "menuBg": "color(primary)"
}

/**
 * 将新样式写入 style 标签
 * @param {string} elNewStyle - 要应用的新样式
 */
export const writeNewStyle = elNewStyle => {
    const style = document.createElement('style')
    style.innerText = elNewStyle
    document.head.appendChild(style)
}

/**
 * 根据主色生成最新的 CSS 样式
 * @param {string} primaryColor - 主色值
 * @returns {Promise<string>} - 更新后的 CSS 文本
 */
export const generateNewStyle = async primaryColor => {
    const colors = generateColors(primaryColor)
    let cssText = await getOriginalStyle()

    Object.keys(colors).forEach(key => {
        cssText = cssText.replace(
            new RegExp('(:|\\s+)' + key, 'g'),
            '$1' + colors[key]
        )
    })

    return cssText
}

/**
 * 根据主色生成颜色值
 * @param {string} primary - 主色值
 * @returns {Object} - 包含颜色值的对象
 */
export const generateColors = primary => {
    if (!primary) return
    const colors = {
        primary
    }
    Object.keys(objJson).forEach(key => {
        const value = objJson[key].replace(/primary/g, primary)
        colors[key] = '#' + rgbHex(color.convert(value))
    })
    return colors
}

/**
 * 获取 element-plus 的默认样式模板
 * @returns {Promise<string>} - 默认样式模板
 */
const getOriginalStyle = async () => {
    const version = (await import('element-plus/package.json')).version
    const url = `https://unpkg.com/element-plus@${version}/dist/index.css`
    const {data} = await axios(url)
    return getStyleTemplate(data)
}

/**
 * 在样式模板中用占位符替换默认颜色值
 * @param {string} data - 原始 CSS 数据
 * @returns {string} - 带占位符的 CSS 模板
 */
const getStyleTemplate = data => {
    const colorMap = {
        '#3a8ee6': 'shade-1',
        '#409eff': 'primary',
        '#53a8ff': 'light-1',
        '#66b1ff': 'light-2',
        '#79bbff': 'light-3',
        '#8cc5ff': 'light-4',
        '#a0cfff': 'light-5',
        '#b3d8ff': 'light-6',
        '#c6e2ff': 'light-7',
        '#d9ecff': 'light-8',
        '#ecf5ff': 'light-9'
    }

    Object.keys(colorMap).forEach(key => {
        const value = colorMap[key]
        data = data.replace(new RegExp(key, 'ig'), value)
    })

    return data
}
